<template>
	<view style="background-color: #fff;border-radius: 5vw;box-shadow: 0 0 0.1vw 0 #ccc;">
		<view class="wanl-share">
			<view class="wanl-share-header">
				<view class="head" style="display: flex;justify-content: space-between;align-items: center;">
					<view class="content">
						<view class="text-lg">分享</view>
					</view>
					<view class="close wlIcon-31guanbi" @tap="close"></view>
				</view>
				<view>
					<uv-tabs :current="current" :list="productData" lineColor="#fd8c00" :activeStyle="{
						color: '#fd8c00',
					}" :scrollable="false" @click="toAnchor"></uv-tabs>
				</view>
			</view>

			<scroll-view class="scroll-x solid-bottom" scroll-x="true" show-scrollbar="false" :scroll-left="scrollAnimation"
				scroll-with-animation>
				<!-- <view class="scroll-item" v-for="(value, index) in providerList" :key="index" v-if="value" @tap="share(value)">
					<view class="icons" :class="value.background"><text :class="value.icon"></text></view>
					<view class="project text-sm">
						<text>{{ value.name }}</text>
					</view>
				</view> -->

				<!-- <wanl-qrcode :url="encodeURIComponent(href)" v-if="current == 0" /> -->

				<!-- 保存图片 -->
				<view v-show="current == 0" class="template-item" v-for="(x, xi) in posterTemplates">
					<!-- <image :src="$wanlshop.oss(x.thumbnail_url, 688, 500)" /> -->
					<view class="haibao" :style="{ backgroundImage: 'url(' + $wanlshop.oss(x.thumbnail_url, 688, 500) + ')' }">
					</view>
				</view>

				<!-- 分享好友 -->
				<view class="share-box" v-show="current == 1">
					<view class="share-top">
						<image src="/static/images/avatarUrl.png"></image>
						<view class="projectName"> {{ projectName }} </view>
					</view>
					<view class="shareText">{{ shareText }}</view>
					<view class="share-image">
						<image class="share-img" :src="$wanlshop.oss(images[0], 668, 500)" mode="aspectFill"></image>
					</view>
				</view>

				<!-- 一键发圈 -->
				<view class="hair-circle" v-show="current == 2">
					<view class="hair-circle-txt">{{ shareText }}</view>
					<view class="hair-circle-list">
						<view class="j-bg" v-for="item in images" :style="{background: `url(${$wanlshop.oss(item)})`}"></view>
					</view>
				</view>
			</scroll-view>

			<view class="foot padding-lr-bj" style="padding: 10rpx 0;">
				<button v-if="current == 0" class="cu-btn round text-bold complete text-white"
					style="border:1rpx solid #fd8c00; background-color: #ffffff; color: #fd8c00; width: 338rpx; height: 68rpx;"
					@tap.stop="save()">保存图片</button>
				<button v-if="current == 1" class="cu-btn round text-bold complete text-white"
					style="border:1rpx solid #fd8c00; background-color: #ffffff; color: #fd8c00; width: 338rpx; height: 68rpx;"
					@tap.stop="copylink()">复制链接</button>
				<!-- #ifdef APP-PLUS -->
				<button v-if="current == 0 || current == 1" class="cu-btn round text-bold complete text-white"
					style="background-color: #fd8c00; width: 338rpx; height: 68rpx; margin-left: 24rpx;" @tap.stop="() => {
					shareType = 0;
					share({ id: 'weixin', type: 'WXSceneSession' });
				}">立即分享</button>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<button v-if="current == 0" class="cu-btn round text-bold complete text-white"
					style="background-color: #fd8c00; width: 338rpx; height: 68rpx; margin-left: 24rpx;"
					@tap.stop="shareNow()">立即分享</button>
				<button id="share" open-type="share" v-if="current == 1" class="cu-btn round text-bold complete text-white"
					style="background-color: #fd8c00; width: 338rpx; height: 68rpx; margin-left: 24rpx;">立即分享</button>
				<!-- #endif -->
				<button v-if="current == 2" class="cu-btn round text-bold complete text-white"
					style="background-color: #fd8c00; width: 338rpx; height: 68rpx;" @tap.stop="copyShare()">复制并分享</button>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * WanlShare 分享 
	 * @description 分享组件 深圳前海万联科技有限公司 https://www.wanlshop.com（除万联官方内嵌系统，未经授权严禁使用）
	 * @著作权：WanlShop 登记号：2020SR0255711 版本：V1.0.0
	 * @property {Number} scrollAnimation 滚动位置
	 * @property {Number} shareType 分享类型 0.图文 1.纯文字 2.纯图片 5.小程序
	 * @property {String} shareTitle 分享标题
	 * @property {String} shareText 分享详情
	 * @property {String} image 分享图片 如果是图文分享，且是ios平台，20kb
	 * @property {String} href 分享链接
	 * @event {Function} change 关闭弹窗
	 * @example <wanl-share :scrollAnimation="scrollAnimation" shareTitle="" shareText="" image="" href="" @change="hideModal"/>
	 */
	import uQRCode from '@/common/uqrcode.js';
	import config from '@/common/config/config';
	export default {
		name: 'WanlShare',
		props: {
			scrollAnimation: {
				type: Number,
				default: 300
			},
			// shareType: {
			// 	type: Number,
			// 	default: 0
			// },
			shareTitle: {
				type: String,
				default: ''
			},
			shareText: {
				type: String,
				default: ''
			},
			image: {
				type: String,
				default: ''
			},
			images: {
				type: Array,
				default: []
			},
			href: {
				type: String,
				default: ''
			},
			isReport: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				projectName: "六只花狗",
				avatarImage: '',
				providerList: [],
				current: 1,
				shareType: '',
				productData: [{
						name: "保存图片"
					},
					{
						name: "分享好友"
					},
					{
						name: "一键发圈"
					},
				],
				posterTemplates: [],
				shareImage: {}, // 分享图片
				shareType: '', // 分享类型
				imagesArray: [],
				appId: 'wx632bc9b5b8fe06ce',
				accessToken: 'access_token',
			};
		},
		created() {
			this.loadData();

			setTimeout(() => {
				this.toAnchor({
					index: 0
				})
			}, 200)

			// uni.getProvider({
			// 	service: 'share',
			// 	success: e => {
			// 		console.log("dddddddddddddddddddddddddd");
			// 		let data = [];
			// 		// #ifdef APP-PLUS
			// 		// for (let i = 0; i < e.provider.length; i++) {
			// 		// 	switch (e.provider[i]) {
			// 		// 		case 'weixin':
			// 		// 			data.push(
			// 		// 				{
			// 		// 					name: '微信好友',
			// 		// 					id: 'weixin',
			// 		// 					icon: 'wlIcon-WeChat',
			// 		// 					background: 'bg-green',
			// 		// 					sort: 0
			// 		// 				},
			// 		// 				{
			// 		// 					name: '微信朋友圈',
			// 		// 					id: 'weixin',
			// 		// 					icon: 'wlIcon-pengyouquan',
			// 		// 					background: 'bg-green',
			// 		// 					type: 'WXSenceTimeline',
			// 		// 					sort: 1
			// 		// 				}
			// 		// 			);
			// 		// 			break;
			// 		// 		case 'sinaweibo':
			// 		// 			data.push({
			// 		// 				name: '新浪微博',
			// 		// 				id: 'sinaweibo',
			// 		// 				icon: 'wlIcon-WeiBo',
			// 		// 				background: 'red',
			// 		// 				sort: 2
			// 		// 			});
			// 		// 			break;
			// 		// 		case 'qq':
			// 		// 			data.push({
			// 		// 				name: 'QQ',
			// 		// 				id: 'qq',
			// 		// 				icon: 'wlIcon-QQ',
			// 		// 				background: 'blue',
			// 		// 				sort: 3
			// 		// 			});
			// 		// 			break;
			// 		// 		default:
			// 		// 			break;
			// 		// 	}
			// 		// }
			// 		// #endif
			// 		data.push(
			// 			// {
			// 			// 	name: '生成海报',
			// 			// 	id: 'poster',
			// 			// 	icon: 'wlIcon-classify',
			// 			// 	background: 'gray',
			// 			// 	sort: 4
			// 			// }
			// 		// 	{
			// 		// 		name: '链接',
			// 		// 		id: 'link',
			// 		// 		icon: 'wlIcon-lianjie',
			// 		// 		background: 'gray',
			// 		// 		sort: 5
			// 		// 	}
			// 		// );
			// 		// if(this.isReport){
			// 		// 	data.push(
			// 		// 		{
			// 		// 			name: '举报',
			// 		// 			id: 'report',
			// 		// 			icon: 'wlIcon-jubao',
			// 		// 			background: 'gray',
			// 		// 			sort: 6
			// 		// 		}
			// 		);
			// 		//}
			// 		this.providerList = data.sort((x, y) => {
			// 			return x.sort - y.sort;
			// 		});
			// 	},
			// 	fail: e => {
			// 		uni.showModal({
			// 			content: '获取分享通道失败',
			// 			showCancel: false
			// 		});
			// 	}
			// });
		},
		mounted() {
			this.imagesArray = [];
			this.images.map(item => {
				this.imagesArray.push(this.$wanlshop.oss(item, 50, 50))
			})
			//this.createLink();
		},
		methods: {
			// 生成短链接
			// createLink() {
			// 	// 首先，确保已经获取到了微信小程序的全局唯一票据（access_token）
			// 	let accessToken = accessToken;
			// 	// 小程序的appId和页面路径
			// 	let appId = this.appId;
			// 	let pagePath = this.href;
			// 	// 生成短链接的API地址
			// 	let generateShortLinkApi = `https://api.weixin.qq.com/wxa/genwxashortlink?access_token=${accessToken}`;
			// 	// 发送POST请求生成短链接
			// 	uni.request({
			// 		url: generateShortLinkApi,
			// 		method: 'POST',
			// 		data: {
			// 			"page_path": pagePath,
			// 			"is_permanent": false
			// 		},
			// 		success: (res) => {
			// 			if (res.statusCode === 200) {
			// 				// 短链接生成成功，可以在res.data.short_link找到生成的短链接
			// 				console.log('短链接:', res.data.short_link);
			// 			} else {
			// 				// 处理错误情况
			// 				console.error('生成短链接失败:', res.errMsg);
			// 			}
			// 		},
			// 		fail: (error) => {
			// 			// 处理请求发送失败的情况
			// 			console.error('请求发送失败:', error);
			// 		}
			// 	});
			// },

			// 分享图片
			async loadData() {
				this.$api.post({
					url: '/wanlshop/common/qrcode',
					success: res => {
						// 下载到本地
						res.forEach((item, index, arr) => {
							if (item.template != 'wanlshopqr') {
								// 远程下载背景
								uni.downloadFile({
									url: this.$wanlshop.oss(item.background_url, 200, 0),
									success: e => {
										item.background_url = e.tempFilePath;
									}
								});
								// 远程下载图标
								uni.downloadFile({
									url: this.$wanlshop.oss(item.logo_src, 80, 80),
									success: e => {
										item.logo_src = e.tempFilePath;
									}
								});
							}
						});
						// 赋值
						this.posterTemplates = [res[res.length - 1]];
						this.shareImage = this.posterTemplates && this.posterTemplates[0];
					}
				});
			},

			// 保存图片
			save() {
				let that = this;
				wx.downloadFile({
					url: that.$wanlshop.oss(that.shareImage.thumbnail_url, 688, 688),
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功'
								})
							},
						});
					},
				})
			},

			// 复制链接
			copylink() {
				// this.$api.get({
				// 	url: `/wanlshop/share/shortlink`,
				// 	data: {
				// 		page_url: this.href, // string 必需通过 Short Link 进入的小程序页面路径，必须是已经发布的小程序存在的页面，可携带 queny，最大1024个字
				// 		page_title: this.shareTitle,    //string 必需页面标题，不能包含违法信息，超过20字符会用..截断代替
				// 		//is_permanent: 0  //number 必需 默认值0。生成的 ShortLink 类型，短期有效:0，永久有效:1
				// 	},
				// 	success: res => {
				// 		uni.setClipboardData({
				// 			data: res.data,
				// 			success: (res) => {
				// 				uni.showToast({
				// 					icon: 'none',
				// 					title: '内容复制成功'
				// 				})
				// 			}
				// 		})
				// 	}
				// })

				uni.setClipboardData({
					data: this.href,
					success: (res) => {
						uni.showToast({
							icon: 'none',
							title: '内容复制成功'
						})
					}
				})
			},

			// 立即分享
			shareNow() {
				// 临时图片
				uni.downloadFile({
					url: this.$wanlshop.oss(this.posterTemplates[0].thumbnail_url, 688, 688),
					success: e => {
						uni.showShareImageMenu({ //分享给朋友
							path: e.tempFilePath,
							success: (res) => {
								console.log("分享成功:", res);
							},
							fail: (err) => {
								console.log("分享取消:", err);
							},
						})
					}
				})
			},

			async share(e) {
				if (e.id == 'poster') {
					this.$wanlshop.to('/pages/user/qrcode/qrcode?url=' + encodeURIComponent(this.href));
				} else if (e.id == 'link') {
					this.$wanlshop.copy(this.href);
				} else if (e.id == 'report') {
					this.complaint();
				} else {
					// if (!this.shareTitle && (this.shareType === 1 || this.shareType === 0)) {
					// 	uni.showModal({
					// 		content: '分享内容不能为空',
					// 		showCancel: false
					// 	});
					// 	return;
					// }

					// if (!this.image && (this.shareType === 2 || this.shareType === 0)) {
					// 	uni.showModal({
					// 		content: '分享图片不能为空',
					// 		showCancel: false
					// 	});
					// 	return;
					// }
					if (this.current == 0) {
						if (!this.shareImage.thumbnail_url && (this.shareType === 2 || this.shareType === 0)) {
							uni.showModal({
								content: '分享图片不能为空',
								showCancel: false
							});
							return;
						}
					}


					// 开始分享
					let shareOPtions = {
						provider: e.id,
						scene: e.type && e.type === 'WXSenceTimeline' ? 'WXSenceTimeline' :
						'WXSceneSession', //WXSceneSession”分享到聊天界面，“WXSenceTimeline”分享到朋友圈，“WXSceneFavorite”分享到微信收藏     
						type: this.shareType,
						success: (e) => {
							uni.showModal({
								content: '已分享',
								showCancel: false
							})
						},
						fail: (e) => {
							uni.showModal({
								content: e.errMsg,
								showCancel: false
							})
						}
					}

					switch (this.shareType) {
						case 0:
							shareOPtions.summary = this.shareText;
							shareOPtions.imageUrl = this.image;
							//shareOPtions.title = this.shareTitle;
							shareOPtions.href = this.href;
							break;
						case 1:
							shareOPtions.summary = this.shareText;
							break;
						case 2:
							//shareOPtions.imageUrl = this.$wanlshop.oss(this.shareImage.thumbnail_url);
							shareOPtions.imageUrl = this.$wanlshop.appstc('/qrcode/logo.png');
							break;
						case 5:
							var pages = getCurrentPages();
							var page = (pages[pages.length - 1]).route;
							shareOPtions.imageUrl = this.image ? this.image : this.$wanlshop.appstc('/qrcode/logo.png');
							shareOPtions.title = this.shareTitle;
							shareOPtions.miniProgram = {
								id: this.$store.state.common.appConfig.mp_weixin_id,
								path: page, //微信小程序ID
								webUrl: this.href,
								type: 0
							};
							break;
						default:
							break;
					}
					if (shareOPtions.type === 0 && plus.os.name === 'iOS') { //如果是图文分享，且是ios平台，则压缩图片 
						shareOPtions.imageUrl = await this.compress();
					}
					if (shareOPtions.type === 1 && shareOPtions.provider === 'qq') { //如果是分享文字到qq，则必须加上href和title
						shareOPtions.href = this.href;
						shareOPtions.title = this.shareTitle;
					}
					uni.share(shareOPtions);

					// if (uni.canIUse('share')) { 

					// } else { 
					// 	// 使用其他分享方式 
					// }
				}
				this.close();
			},

			// 关闭模态框
			close() {
				this.$emit('change');
			},

			// 举报商品
			// complaint(){
			// 	this.$emit('change','complaint');
			// },

			// 切换tab
			toAnchor(val) {
				this.current = val.index;
			},

			// 保存图片到相册
			saveImagesToAlbum(urls) {
				if (urls.length == 0) {
					uni.showToast({
						icon: 'none',
						title: '内容已复制'
					})
					return false;
				}
				const url = urls.shift(); // 获取数组中的第一个图片URL
				uni.downloadFile({
					url: url,
					success: downloadResult => {
						//if (downloadResult.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: downloadResult.tempFilePath,
							success: () => {
								// 递归保存剩余图片
								this.saveImagesToAlbum(urls);
							},
						});
						//}
					},
					fail: () => {
						// 递归保存剩余图片
						this.saveImagesToAlbum(urls);
					}
				});
			},

			// 复制并分享
			copyShare() {
				uni.setClipboardData({
					data: this.shareText
				})
				const urls = JSON.parse(JSON.stringify(this.imagesArray));
				this.saveImagesToAlbum(urls);
			},
		}
	};
</script>
<style lang="scss">
	.wanl-share-header {
		background-color: #ffffff;
	}

	/* 分享 */
	.wanl-share {
		min-height: 50rpx;
		padding-bottom: 0px;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.wanl-share .head {
		padding: 25rpx 25rpx 10rpx 25rpx;
	}

	.wanl-share .head .content {
		justify-content: left;
		//margin-left: 16rpx;
		width: 100%;
		font-weight: 700;
		color: #000000;
	}

	.wanl-share .scroll-x {
		white-space: nowrap;
		width: 100%;
		padding: 32rpx 0;
		text-align: left;
		height: 250rpx;
		background-color: #f6efe9;
	}

	.wanl-share .scroll-x .scroll-item {
		display: inline-block;
		font-size: 36rpx;
		margin-left: 36rpx;
		text-align: center;
	}

	.wanl-share .scroll-x .scroll-item button {
		line-height: 1;
		background-color: rgba(0, 0, 0, 0);
		border: 0;
		padding: 0;
	}

	.wanl-share .scroll-x .scroll-item button:after {
		border: 0;
	}

	.wanl-share .scroll-x .scroll-item:last-child {
		margin-right: 36rpx;
	}

	.wanl-share .scroll-x .scroll-item .icons {
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx;
		border-radius: 9999rpx;
		margin: 0 auto;
		font-size: 40rpx;
		display: block;
	}

	.wanl-share .scroll-x .scroll-item .icons.gray {
		color: #606060;
		background-color: #f5f5f5;
	}

	.wanl-share .scroll-x .scroll-item .icons.red {
		color: #ffffff;
		background-color: #e6162c;
	}

	.wanl-share .scroll-x .scroll-item .icons.blue {
		color: #ffffff;
		background-color: #3e92e8;
	}

	.wanl-share .scroll-x .scroll-item .project {
		margin-top: 25rpx;
	}

	.wanl-share .footer {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
	}

	.solid-bottom {
		height: 904rpx !important;
		padding: 32rpx !important;
		margin-top: -5rpx;
	}


	.template-item {
		width: 688rpx;
		height: 840rpx;
		border-radius: 16rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 16rpx;
		}
	}

	// 好友分享
	.share-box {
		background-color: #ffffff;
		border-radius: 16rpx;
		margin-top: 32rpx;
		margin-bottom: 32rpx;
		//height: 704rpx;
		min-height: 668rpx;
		padding: 24rpx;

		.share-top {
			display: flex;
			align-items: center;

			image {
				width: 80rpx;
				height: 80rpx;
			}

			.projectName {
				margin-left: 16rpx;
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
			}
		}

		.shareText {
			font-weight: 600;
			font-size: 28rpx;
			white-space: normal;
			margin-top: 16rpx;
			margin-bottom: 16rpx;
		}

		.share-image {
			width: 636rpx;
			height: 540rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 16rpx;
			}
		}
	}

	// 一键发圈
	.hair-circle {
		background-color: #ffffff;
		border-radius: 16rpx;
		margin-top: 32rpx;
		margin-bottom: 32rpx;
		height: 774rpx;
		padding: 24rpx;

		.hair-circle-txt {
			font-size: 28rpx;
			font-weight: bold;
			margin-bottom: 24rpx;
			width: 100%;
			white-space: break-spaces;
		}

		.hair-circle-list {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 14rpx;

			.j-bg {
				background-position: center !important;
				background-repeat: no-repeat !important;
				background-size: cover !important;
				width: 100%;
				padding-top: 100%;
			}
		}
	}

	.haibao {
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		width: 688rpx;
		height: 838rpx;
	}

	.share-img {
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		width: 688rpx;
		height: 430rpx;
	}
</style>